
const util = require('../../utils/util.js')
import {calendar} from '../../utils/calendar'
import {FamilyTreeDrawer} from '../../utils/drawer/family_tree_drawer'

const app = getApp()
var scope  //在this无效时代替this

Page({
  onShareAppMessage() {
    return {
      title: 'canvas',
      path: 'page/component/pages/canvas-2d/canvas-2d'
    }
  },
  data: {
    canIUse: true,
  },
  onReady() {
    var leapMonth = calendar.leapMonth(1987)
    var days = calendar.leapDays(1987)
    var num = calendar.monthDays(1987, 6)
    console.log('+++++++++++++++', leapMonth, days, num)

    this.tree_drawer = new FamilyTreeDrawer({
      can_select_person: true,   //是否可以选中人
      cancel_select_person: false,  //点击空白位置(人以外的位置)是否可取消选中人
      can_long_press_person: true  //是否支持长按人
    }) //家族树绘制器

    // 解决基础库小于 2.7.0 的兼容问题
    const { SDKVersion } = wx.getSystemInfoSync();
    console.log(SDKVersion)
    if(app.compareVersion(SDKVersion, '2.7.0') < 0) {
      console.log('123')
      this.setData({
        canIUse: false,
      })
    } else {
      // canvas2D
      this.position2D = {
        width: 0,   //画布总宽度和高度
        height: 0,
        scale: 1,
      }
      this.x = -100;
      wx.createSelectorQuery()
        .select('#canvas2D')
        .fields({
          node: true,
          size: true,
        })
        .exec(this.init.bind(this))
    }

    //登录
    console.log('test-----', util.formatTime(new Date()))
    scope = this
    this.tryLogin()
  },

  //每次显示都会调用一遍
  onShow() {
    if (this.tree_drawer) {
      this.tree_drawer.ClearTapCache()
    }
  },

  // 登录
  tryLogin() {
    app.globalData.session = wx.getStorageSync('localSession')
    if (app.globalData.session.length == 0) {
      //没有session,要调用接口获取
      wx.login({
        //获取session
        success: res => {
          app.httpRequest('code_login', {
            code: res.code
          }, res => {
            //成功
            console.log('code login succeed', res)
            wx.setStorageSync('localSession', res.session)
            app.globalData.session = res.session

            //session登录
            let session = res.session
            console.log('current session: ', session)
            app.httpRequest('session_login', {}, res => {
              console.log('user info: ', res)
              let userinfo = res
              console.log('user info: ', userinfo)
        
              let family_id = userinfo.curr_family_id
              app.globalData.curr_person = userinfo.curr_user_id
              app.globalData.select_family_id = family_id
              this.tree_drawer.SetData(family_id, userinfo.family_data)
              this.tree_drawer.SwitchFamily(family_id)
            }, res => {
              console.log('get user info failed: ', res)
            })

          }, res => {
            //失败
            console.log('code login request failed: ', res)
          })
        },
        fail: res => {
          console.log('weixin login failed: ', res)
        }
      })
    }else {

      //session登录
      let session = app.globalData.session
      console.log('current session: ', session)
      app.httpRequest('session_login', {}, res => {
        console.log('user info: ', res)
        let userinfo = res
        console.log('user info: ', userinfo)
  
        let family_id = userinfo.curr_family_id
        app.globalData.curr_person = userinfo.curr_user_id
        app.globalData.select_family_id = family_id
        this.tree_drawer.SetData(family_id, userinfo.family_data)
        this.tree_drawer.SwitchFamily(family_id)
      }, res => {
        console.log('get user info failed: ', res)
        if (res.code == -4 || res.code == -5) {
          //session错误
          wx.setStorageSync('localSession', '')
          this.tryLogin()   //失败了，重新获取token
          return {notip: true}
        }
        
      })
  
    }
  },

  init(res) {
    const width = res[0].width
    const height = res[0].height

    const canvas = res[0].node
    // 不支持2d
    if (!canvas) {
      this.setData({
        canIUse: false,
      })
      return
    }
    const ctx = canvas.getContext('2d')

    const dpr = 750 / wx.getSystemInfoSync().windowWidth  //听说getSystemInfoSync返回的pixelRatio有可能不准。
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)

    this.tree_drawer.SetContext(ctx, width, height) //传入画布及画布整个的大小

    //渲染循环
    const renderLoop = () => {
      this.tree_drawer.Render()
      canvas.requestAnimationFrame(renderLoop)
    }
    canvas.requestAnimationFrame(renderLoop)

  },

  onTouchStart(e) {
    if (e.touches && e.touches.length == 1){
      //单指点击
      console.log('+++++++++ single start', e)
      this.tree_drawer.OnDragStart(e)
      this.single_finger = true
      this.double_finger = false
    }
    else if (e.touches && e.touches.length == 2){
      console.log('+++++++++++++double start', e)
      this.tree_drawer.OnScaleStart(e)
      this.single_finger = false
      this.double_finger = true
    }
  },

  onTouchMove(e) {
    if (e.touches && e.touches.length == 1){
      //单指点击
      this.tree_drawer.OnDragging(e)
    }
    else if (e.touches && e.touches.length == 2){
      //双指
      this.tree_drawer.OnScaling(e)
    }
  },

  onTouchCancel(e) {
    if (this.single_finger) {
      this.tree_drawer.OnDragEnd(e)
    }
    if (this.double_finger) {
      this.tree_drawer.OnScaleEnd(e)
    }
  },

  onTouchEnd(e) {
    if (this.single_finger) {
      this.tree_drawer.OnDragEnd(e)
    }
    if (this.double_finger) {
      this.tree_drawer.OnScaleEnd(e)
    }
  },

  onUnload() {
    // clearInterval(this.interval)
  },

  //切换家族回调
  bindTapSelectFamily() {
    if (app.globalData.select_family_id == -1) {
      return
    }

    wx.navigateTo({
      url: '../family/select?select_family=' + app.globalData.select_family_id
    })

  },

  //查看帮助回调
  bindTapLookHelp() {
    console.log('look help')
    wx.navigateTo({
      url: '../help/help'
    })
  },

  //关闭家族选择弹框
  bindCloseFamilySelect(e) {
    // this.setData({
    //   familyDialogShow: false
    // })
  },

  //更改家族排序
  bindTapFamilyPriority(e) {
    if (app.globalData.select_family_id == -1) {
      return
    }
    console.log('change family priority: ', app.globalData. select_family_id)
    let index = -1
    let family_list = this.data.family_list
    for (let i = 0; i < family_list.length; i++) {
      if (family_list[i].family_id == app.globalData. select_family_id) {
        index = i
      }
    }
    if (index == -1) {
      return
    }

    if (index > 0) {
      [family_list[index],family_list[index - 1]] = [family_list[index - 1],family_list[index]]
      this.setData({
        family_list: family_list,
        family_scroll_toview: 'family-item-' + app.globalData.select_family_id
      })
    }    
  },

  bindTapEditRelation() {
    wx.navigateTo({
      url: '../relation/edit_relation_page'
    })
  },

  //修改人员后刷新人员数据
  refreshFamilyData(data) {
    console.log('refresh family data ...')
    let family_id = app.globalData.select_family_id
    this.tree_drawer.SetData(family_id, data)
    this.tree_drawer.SwitchFamily(family_id)
  }

})
